package com.frame.pageform.component.tree;

import java.util.ArrayList;
import java.util.List;

import com.frame.pageform.component.BaseJsonObject;

/**
 * @Title: 系统
 * @Description:
 * @Copyright: Copyright (c) 2014
 * @Company:
 * @author 王海锋
 * @CreatedTime:2014-3-12 下午11:39:49
 * @version 1.0
 */

public class EasyuiTreeJsonObject extends BaseJsonObject{

    private List nodeList;

    public EasyuiTreeJsonObject(){
        nodeList=new ArrayList();
    }
    public void add(TreeNode node){
        nodeList.add(node);
    }
    public String toString(){
        if(nodeList==null)
            return "";
        StringBuffer sb = new StringBuffer();
        try{
            sb.append("[");
            for(int i=0;i<nodeList.size();i++){
                if(i>0)
                    sb.append(",");
                sb.append(toString((TreeNode)nodeList.get(i)));
            }
            sb.append("]");
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
    public String toString(TreeNode node) throws Exception{
        StringBuffer sb = new StringBuffer();
        sb.append("\"id\":"+quote(node.getId()));
        sb.append(",\"text\":"+quote(node.getText()));
        if(node.isLazy()){
            //动态加载树
            if(node.getChildSize()==null)
                throw new Exception("TreeNode的childSize属性没有赋值");
            if(node.getChildSize().intValue()>0){
                if(node.isExpand())
                    sb.append(",\"state\":\"open\"");
                else
                    sb.append(",\"state\":\"closed\"");
            }
        }else{
            if(node.getChildList()!=null && node.getChildList().size()>0){
                if(node.isExpand())
                    sb.append(",\"state\":\"open\"");
                else
                    sb.append(",\"state\":\"closed\"");
            }
        }
        if(node.isChecked())
            sb.append(",\"checked\":"+true);
        if(node.getUrl()!=null)
            sb.append(",\"url\":"+quote(node.getUrl()));
        if(node.getIcon()!=null && !"".equals(node.getIcon()))
            sb.append(",\"iconUrl\":"+quote(node.getIcon()));
        List clist=node.getChildList();
        if(clist!=null && clist.size()>0){
            String cstr="";
            for(int i=0;i<clist.size();i++){
                TreeNode cnode=(TreeNode)clist.get(i);
                if(i>0)
                    cstr+=",";
                cstr+=toString(cnode);

            }
            sb.append(",\"children\":["+cstr+"]");
        }
        return "{"+sb.toString()+"}";
    }
}
